$(function () {

    initWholeTree();
    
    $('#menuAddBtn').click(function () {
        var name=$('[name="name"]').val();
        var url=$('[name="url"]').val();
        var icon=$('[name="icon"]:checked').val();
        var pid=window.menuId;

        if(name.length==0){
            layer.msg('菜单名称不能为空！');
            return;
        }
        if(url.length==0){
            layer.msg('url不能为空！');
            return;
        }

        //发送ajax请求
        $.ajax({
            "url":"/menu/save",
            "type":"post",
            "dataType":"json",
            "data":{
                "name":name,
                "url":url,
                "pid":pid,   // 当前操作的节点是新节点的父节点
                "icon":icon
            },
            success:function (ajaxResult) {
                if(ajaxResult.result == "FAILED") {
                    layer.msg(response.message);
                }
                if(ajaxResult.result == "SUCCESS") {
                    layer.msg("操作成功！");

                    //刷新
                    initWholeTree();
                }
            }
        });
        //隐藏模态框
        $('#menuAddModal').modal('hide');
    });

    $('#menuEditBtn').click(function () {
        var name=$('#menuEditModal [name="name"]').val();
        var url=$('#menuEditModal [name="url"]').val();
        var icon=$('#menuEditModal [name="icon"]:checked').val();
        var id =window.menuId;

        if(name.length==0){
            layer.msg('菜单名称不能为空！');
            return;
        }
        if(url.length==0){
            layer.msg('url不能为空！');
            return;
        }

        //发送请求
        $.ajax({
            "url":"/menu/update",
            "type":"post",
            "dataType":"json",
            "data":{
                "id":window.menuId,
                "name":name,
                "url":url,
                "icon":icon
            },
            success:function (response) {
                var result = response.result;

                if(result == "SUCCESS") {
                    layer.msg("操作成功！");

                    initWholeTree();
                }

                if(result == "FAILED") {
                    layer.msg(response.message);
                }
            }
        });
        //隐藏模态框
        $('#menuEditModal').modal('hide');
    });
});

//更换图标
function showMyIcon(treeId, treeNode) {
    console.log(treeNode.tId);
    console.log(treeNode.id);
    console.log(treeNode.icon);
    console.log(treeNode.name);
    console.log(treeNode.level);

    var newClass=treeNode.icon;
    var spanid=treeNode.tId+"_ico";
    $('#'+spanid).removeClass().addClass(newClass).css("background","");
}

//生成按钮组
function generateBtnGrp(treeNode){
    //treeDemo_20_btnGrp
    var btnGrpSpanId= treeNode.tId+"_btnGrp";
    var menuId=treeNode.id;

    // 声明三种按钮
    var addBtn = "<a onclick='showAddModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='添加子节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-plus rbg'></i></a>";
    var editBtn = "<a onclick='showEditModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='编辑节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-edit rbg'></i></a>";
    var removeBtn = "<a onclick='showConfirmModal(this)' id='"+menuId+"' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='删除节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-times rbg'></i></a>";

    // 生成span标签对应的jQuery对象
    var $span = $("<span id='"+btnGrpSpanId+"'></span>");
    //获取菜单的level
    var level=treeNode.level;
    if(level==0){
        $span.append(addBtn);
    }else if(level==1){
        if(treeNode.children.length>0){
            $span.append(addBtn+" "+editBtn);
        }else{
            $span.append(addBtn+" "+editBtn+" "+removeBtn);
        }
    }else{
        $span.append(editBtn+" "+removeBtn);
    }
    return $span;

}

//鼠标悬浮
function addHoverDom(treeId, treeNode){

    //如果按钮组存在，则不进行添加
    var btnGrpSpanId = treeNode.tId + "_btnGrp";
    if($('#'+btnGrpSpanId).length>0){
        return;
    }
    //得到按钮组
    var btnGrp=generateBtnGrp(treeNode);

    //找到菜单中的超链接
    var anchorId =treeNode.tId+"_a";
    $('#'+anchorId).append(btnGrp);
}

//鼠标移出
function removeHoverDom(treeId, treeNode){
    //找到按钮组 删除
    var btnGrpSpanId = treeNode.tId + "_btnGrp";
    $('#'+btnGrpSpanId).remove();
}

//添加子节点
function showAddModal(obj) {
    //获取menuid保存到全局变量
    window.menuId=$(obj).attr("id");
    //打开模态框
    $('#menuAddModal').modal('show');
}

//加载zTree
function initWholeTree() {
    var setting = {
        "view": {
            //设置自定义图标
            "addDiyDom": showMyIcon,
            "addHoverDom": addHoverDom,
            "removeHoverDom": removeHoverDom
        },
        "data": {
            "key": {
                "url": "notExistsProperty" // 阻止点击节点后跳转
            }
        }
    };

    $.ajax({
        "url":"/menu/get/whole/tree",
        "type":"post",
        "dataType":"json",
        "success":function(ajaxResult){
            if(ajaxResult.result=="SUCCESS"){
                var zNodes=ajaxResult.data;
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            }else{
                layer.msg("加载菜单数据失败！原因是："+response.message);
            }
        },
        "error":function(response){
            layer.msg("加载菜单数据失败！原因是："+response.message);
        }
    });
}

function showEditModal(obj) {
    //获取menuid保存到全局变量
    window.menuId=$(obj).attr("id");
    //打开模态框
    $('#menuEditModal').modal('show');

    //发送ajax,进行数据回显
    $.ajax({
        "url":"/menu/get/"+window.menuId,
        "type":"get",
        "dataType":"json",
        "success":function(response){
            if(response.result=="SUCCESS"){
                $('#menuEditModal [name="name"]').val(response.data.name);
                $('#menuEditModal [name="url"]').val(response.data.url);
                $('#menuEditModal [name="icon"][value="'+response.data.icon+'"]').attr("checked",true);
            }else{
                layer.msg(response.message);
            }
        }
    });
}

//删除
function showConfirmModal(obj) {
    //获取menuid保存到全局变量
    window.menuId=$(obj).attr("id");
    //获取节点名称
    var name=$(obj).parent().prev().text();

    var r=confirm("确认删除"+name+"菜单吗？");
    if(r==false){
        return;
    }

    //发送删除请求
    $.ajax({
        "url":"/menu/delete/"+window.menuId,
        "type":"get",
        "dataType":"json",
        "success":function(response) {
            if(response.result=="SUCCESS"){
                layer.msg("操作成功");
                //刷新
                initWholeTree();
            }else{
                layer.msg("删除失败，请联系管理员");
            }
        }
    });

}